package com.poptap.base.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Order;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import com.poptap.base.domain.Region;
import com.poptap.base.util.CollectionUtil;
import com.poptap.base.util.StringUtil;

@Service
public class RegionServiceImpl implements RegionService {

	@Autowired
	private MongoTemplate template;
	
	@Override
	public boolean createRegion(String name) {
		if(StringUtil.isEmptyOrWhitespaceOnly(name)) {
			return false;
		}
		Region region = new Region();
		region.setName(name);
		region.setCreateTime(new Date());
		template.save(region);
		return true;
	}

	@Override
	public boolean updateRegion(String id, String name) {
		if(StringUtil.isEmptyOrWhitespaceOnly(name)) {
			return false;
		}
		Region region = find(id);
		region.setName(name);
		template.save(region);
		return true;
	}

	@Override
	public List<Region> findAllRegions() {
		Query query = new Query();
		query.sort().on("createTime", Order.ASCENDING);
		List<Region> regions = template.find(query, Region.class);
		if(CollectionUtil.isEmpty(regions)) {
			return new ArrayList<Region>();
		} else {
			return regions;
		}
	}

	@Override
	public Region find(String id) {
		return template.findOne(new Query(Criteria.where("id").is(new ObjectId(id))), Region.class);
	}

}
